import useIsomorphicLayoutEffect from "../hooks/useIsomorphicLayoutEffect";
import Offset from "../portal/Offset";
import Position from "../portal/Position";
import calculatePosition from "../utils/calculatePosition";

import { RefObject } from "react";

const usePosition = (
  contentRef: RefObject<HTMLElement>,
  targetRef: RefObject<HTMLElement>,
  anchorRef: RefObject<HTMLElement>,
  position: Position,
  offset: Offset
): void => {
  useIsomorphicLayoutEffect(() => {
    const targetEle = targetRef.current;
    const contentEle = contentRef.current;
    const anchorEle = anchorRef.current;
    if (!contentEle || !targetEle || !anchorEle) {
      return;
    }

    const anchorRect = anchorEle.getBoundingClientRect();
    const { top, left } = calculatePosition(
      contentEle,
      targetEle,
      position,
      offset
    );
    contentEle.style.top = `${top - anchorRect.top}px`;
    contentEle.style.left = `${left - anchorRect.left}px`;
  }, []);
};

export default usePosition;
